# app/course_mgmt.py

from flask import Blueprint, request, jsonify, session, abort
from functools import wraps
from . import db
from .models import Course, User

course_bp = Blueprint('course_mgmt', __name__, url_prefix='/api/courses')

def login_required(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        uid = session.get('user_id')
        if not uid:
            abort(401)
        return f(*args, **kwargs)
    return wrapped

@course_bp.before_request
@login_required
def ensure_login():
    pass

@course_bp.route('', methods=['GET'])
def list_courses():
    uid = session['user_id']
    courses = Course.query.filter_by(owner_id=uid).order_by(Course.seq).all()
    return jsonify([{"id": c.id, "name": c.name} for c in courses]), 200

@course_bp.route('', methods=['POST'])
def create_course():
    uid = session['user_id']
    data = request.get_json() or {}
    name = data.get('name','').strip()
    if not name:
        return jsonify({"error":"课程名必填"}),400
    # 计算最大 seq +1
    max_seq = db.session.query(db.func.max(Course.seq)).filter_by(owner_id=uid).scalar() or 0
    c = Course(name=name, owner_id=uid, seq=max_seq+1)
    db.session.add(c); db.session.commit()
    return jsonify({"id":c.id, "name":c.name}),201

@course_bp.route('/<int:cid>', methods=['PUT'])
def update_course(cid):
    uid = session['user_id']
    c = Course.query.filter_by(id=cid, owner_id=uid).first_or_404()
    data = request.get_json() or {}
    name = data.get('name','').strip()
    if not name:
        return jsonify({"error":"课程名必填"}),400
    c.name = name
    db.session.commit()
    return jsonify({"message":"更新成功"}),200

@course_bp.route('/<int:cid>', methods=['DELETE'])
def delete_course(cid):
    uid = session['user_id']
    c = Course.query.filter_by(id=cid, owner_id=uid).first_or_404()
    db.session.delete(c); db.session.commit()
    # 重新压缩 seq
    courses = Course.query.filter_by(owner_id=uid).order_by(Course.seq).all()
    for idx,c in enumerate(courses, start=1):
        c.seq = idx
    db.session.commit()
    return jsonify({"message":"删除成功"}),200

@course_bp.route('/<int:cid>/move', methods=['POST'])
def move_course(cid):
    """请求 body: { dir: 'up'|'down' }"""
    uid = session['user_id']
    c = Course.query.filter_by(id=cid, owner_id=uid).first_or_404()
    dir_ = request.get_json().get('dir')
    # 找到要交换的项
    if dir_=='up':
        other = Course.query.filter(Course.owner_id==uid, Course.seq < c.seq).order_by(Course.seq.desc()).first()
    else:
        other = Course.query.filter(Course.owner_id==uid, Course.seq > c.seq).order_by(Course.seq.asc()).first()
    if other:
        c.seq, other.seq = other.seq, c.seq
        db.session.commit()
    return jsonify({"message":"移动成功"}),200
